package com.power.powercash.report;

import java.lang.reflect.Method;

/**
 *
 * @author f6036477
 */
public class Extractor {

	private Field field;


	public Extractor() {
		field = null;
	}


	public Extractor(Field field) {
		this.field = field;
	}


	public Field getField() {
		return field;
	}


	public void setField(Field field) {
		this.field = field;
	}


	public Object extract() {
		if(field == null || field.infos().isEmpty()) return null;

		Object o = field.getObject();
		for(Info i : field.infos()) {
			o = this.extract(o, i);
			field.rtype = i.getReturnType();
		}
		field.ret = o;
		return field.ret;
	}


	private Object extract(Object o, Info i) {
		if(o == null || i == null) return null;
		try {
			Method m = i.getType().getMethod(i.getMethod());
			return m.invoke(o);
		} catch(Exception ex) {
			//ex.printStackTrace();
			return null;
		}
	}


	public static void main(String[] args) {
		class C {
			private int i = 5;
			public int getValue() { return i; }
		}
		
		class B {
			private C c = new C();
			public C getC() { return c; }
		}

		class A {
			private B b = new B();
			public B getB() { return b; }
		}

		A a = new A();

		Field f = new Field(a);
		f.infos().add(new Info(A.class, "getB", B.class));
		f.infos().add(new Info(B.class, "getC", C.class));
		//f.infos().add(new Info(C.class, "getValue", Integer.class));

		Extractor ext = new Extractor(f);
		ext.extract();
		System.out.println(f.getReturnType().getName() + " - " + f.getReturn());
		Integer i = f.castReturn();
		System.out.println(i);
	}

}
